package leetcode.code1733;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution2 implements IDebug {

	public int minimumTeachings(int n, int[][] languages, int[][] friendships) {
		Map<Integer, Set<Integer>> map = new HashMap<>();
		for (int i = 0; i < languages.length; i++) {
			int[] lan = languages[i];
			Set<Integer> set = new HashSet<>();
			for (int j = 0; j < lan.length; j++) {
				set.add(lan[j]);
			}
			map.put(i + 1, set);
		}
		Set<Integer> ships = new HashSet<>();
		for (int i = 0; i < friendships.length; i++) {
			int[] friend = friendships[i];
			Set<Integer> lan0 = map.get(friend[0]);
			Set<Integer> lan1 = map.get(friend[1]);
			if (!this.same(lan0, lan1)) {
				ships.add(friend[0]);
				ships.add(friend[1]);
			}
		}
		int ans = Integer.MAX_VALUE;
		for (int i = 1; i <= n; i++) {
			int cur = 0;
			for (int friend : ships) {
				Set<Integer> lan0 = map.get(friend);
				if (!lan0.contains(i)) {
					cur += 1;
				}
			}
			ans = Math.min(ans, cur);
		}
		return ans;
	}

	private boolean same(Set<Integer> lan0, Set<Integer> lan1) {
		for (Integer l : lan1) {
			if (lan0.contains(l)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void debug4() {
		H.compare(2, this.minimumTeachings(3, H.str2array1("[[2],[1,3],[1,2],[3]]"),
				H.str2array1("[[1,4],[1,2],[3,4],[2,3]]")));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
